package netcracker;

import java.io.File;
import java.util.List;
import java.util.Stack;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 
 * @author den
 *
 */
public class Finder {
	private Pattern p = null;
	private Matcher m = null;
	
	Stack st = new Stack();
	
	private String str;
	
	public Finder(){
		
	}
	
	private boolean isRegxp(String fileName){
		m = p.matcher(fileName);
		if (m.matches()){
			return true;
		}
		else {
			return false;
		}
	}
	
	public List findAll(String path, String regexp, int vol) throws Exception{
		str = regexp;
		return find(path, regexp, vol);
	}
	
	private List find(String path, String regexp, int vol) throws Exception{
		File mainDirectory = new File(path);
		if (!mainDirectory.exists()){
			throw new Exception("This way doesn't exist");
		}
		p = Pattern.compile(regexp);
		ArrayList res = new ArrayList(100);
		search(mainDirectory, res, vol);
		p = null;
		return res;
	}
	
	private void search(File mainDirectory, List res, int vol){
		File[] files = mainDirectory.listFiles();
		for (int i=0; i<files.length; i++){
			st.push(files[i]);
		}
		files = null;
		while (st.size() > 0){
			File tmpFile = (File)st.pop();
			if (tmpFile.isDirectory()){
				files = tmpFile.listFiles();
				for (int i=0; i<files.length; i++){
					st.push(files[i]);
				}
			}
			else{
				switch (vol){
				case 0:
					if (isRegxp(tmpFile.getName())){
						res.add(tmpFile);
					}
					break;
				case 1:
					if (tmpFile.getName().startsWith(str))
						res.add(tmpFile);
					break;
				}
			}
		}
	}
	
}
